import {
  Component,
  OnInit,
  Directive,
  HostListener,
  Input
} from "@angular/core";
import {
  AsyncValidator,
  NG_ASYNC_VALIDATORS,
  ValidationErrors,
  AbstractControl,
  FormBuilder,
  FormGroup,
  Validators,
  ControlValueAccessor,
  NG_VALUE_ACCESSOR,
  FormControl,
  NgControl
} from "@angular/forms";

@Directive({
  selector: "[appLimitMask]"
})
export class LimitMaskDirective {
  @Input()
  max: string;
  @Input()
  min: string;
  constructor(public model: NgControl) {}

  @HostListener("change", ["$event"])
  onChange(e) {
    let newVal = "";
    if (Number(e.target.value) >= Number(this.max)) {
      newVal = this.max;
      this.model.valueAccessor.writeValue(newVal);
    }
    if (Number(e.target.value) <= Number(this.min)) {
      newVal = this.min;
      this.model.valueAccessor.writeValue(newVal);
    }
  }
}
